//
//  WXPGlobalFeedviewBack.m
//  全局的问题反馈
//
//  Created by wxp on 2025/2/27.
//

#import "WXPGlobalFeedbackView.h"

@interface WXPGlobalFeedbackView ()<UITextViewDelegate>

@end

@implementation WXPGlobalFeedbackView

#pragma mark - lazy
- (UIView *)viewBack{
    if (_viewBack == nil) {
        _viewBack = [UIView new];
        _viewBack.backgroundColor = COLOR_WHITE;
        _viewBack.width = SCREEN_WIDTH-2*LEFT_MARDIN;
        [GlobalMethod setRoundView:_viewBack color:[UIColor clearColor] numRound:16 width:0];
    }
    return _viewBack;
}
- (UILabel *)labelTitle{
    if (_labelTitle == nil) {
        _labelTitle = [UILabel new];
        _labelTitle.textColor = COLOR_BLACK;
        _labelTitle.fontNum = 18;
    }
    return _labelTitle;
}
- (UIButton *)btnClose{
    if (_btnClose == nil) {
        _btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnClose.tag = 1;
        [_btnClose addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btnClose setImage:[UIImage imageNamed:@"icon-login-close"] forState:UIControlStateNormal];
        _btnClose.widthHeight = XY(24+2*LEFT_MARDIN, 24+2*LEFT_MARDIN);
    }
    return _btnClose;
}
- (UILabel *)labelContent{
    if (_labelContent == nil) {
        _labelContent = [UILabel new];
        _labelContent.textColor = COLOR_CONTENT;
        _labelContent.fontNum = 12;
    }
    return _labelContent;
}
- (UIView *)viewTextBack{
    if (_viewTextBack == nil) {
        _viewTextBack = [UIView new];
        _viewTextBack.backgroundColor = COLOR_BACKGROUND;
        [_viewTextBack addSubview:self.labelNum];
        [_viewTextBack addSubview:self.textView];
        [_viewTextBack addSubview:self.labelPlaceholder];
    }
    return _viewTextBack;
}
- (UITextView *)textView{
    if (!_textView) {
        _textView = [UITextView new];
        _textView.backgroundColor = COLOR_BACKGROUND;
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize: 12];
        _textView.textColor = COLOR_BLACK;
    }
    return _textView;
}
- (UILabel *)labelPlaceholder{
    if (_labelPlaceholder == nil) {
        _labelPlaceholder = [UILabel new];
        _labelPlaceholder.textColor = COLOR_CONTENT;
        _labelPlaceholder.fontNum = 12;
        [_labelPlaceholder fitTitle:@"Por favor inserte" variable:0];
    }
    return _labelPlaceholder;
}
- (UILabel *)labelNum{
    if (_labelNum == nil) {
        _labelNum = [UILabel new];
        _labelNum.textColor = COLOR_LIGHT_GRAY;
        _labelNum.fontNum = 12;
    }
    return _labelNum;
}

- (UIButton *)btnOK{
    if (_btnOK == nil) {
        _btnOK = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnOK.tag = 2;
        [_btnOK addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        _btnOK.backgroundColor = COLOR_PRIMARY;
        [_btnOK setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _btnOK.titleLabel.font = [UIFont boldSystemFontOfSize: 14];
        [_btnOK setTitle:@"Entregar" forState:(UIControlStateNormal)];
        _btnOK.userInteractionEnabled = false;
        _btnOK.alpha = 0.5;
    }
    return _btnOK;
}
- (UILabel *)labelSubContent{
    if (_labelSubContent == nil) {
        _labelSubContent = [UILabel new];
        _labelSubContent.textColor = COLOR_CONTENT;
        _labelSubContent.fontNum = 12;
        _labelSubContent.numberOfLines = 0;
        _labelSubContent.lineSpace = 2;
    }
    return _labelSubContent;
}
- (UIView *)viewPhoneBack{
    if (_viewPhoneBack == nil) {
        _viewPhoneBack = [UIView new];
        _viewPhoneBack.backgroundColor = COLOR_WHITE;
    }
    return _viewPhoneBack;
}
- (UILabel *)labelPhone{
    if (_labelPhone == nil) {
        _labelPhone = [UILabel new];
        _labelPhone.textColor = COLOR_BLACK;
        _labelPhone.fontNum = 14;
    }
    return _labelPhone;
}
-(UIButton *)btnCopy{
    if (_btnCopy == nil) {
        _btnCopy = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnCopy.tag = 3;
        [_btnCopy addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        _btnCopy.backgroundColor = COLOR_PRIMARY;
        [_btnCopy setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _btnCopy.titleLabel.font = [UIFont boldSystemFontOfSize: 14];
        [_btnCopy setTitle:@"Copy" forState:(UIControlStateNormal)];
    }
    return _btnCopy;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.maxCharacterCount = 200;
        self.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT);
        self.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.4];
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self addGestureRecognizer:tapGestureRecognizer];
        [self addSubView];
        [self requestCustomerServiceInfo];
    }
    return self;
}

//添加subview
- (void)addSubView{
    [self addSubview:self.viewBack];
    [self.viewBack addSubview:self.btnClose];
    [self.viewBack addSubview:self.labelTitle];
    [self.viewBack addSubview:self.labelContent];
    [self.viewBack addSubview:self.viewTextBack];
    [self.viewBack addSubview:self.btnOK];
    [self.viewBack addSubview:self.labelSubContent];
    [self.viewBack addSubview:self.btnCopy];
    [self.viewBack addSubview:self.viewPhoneBack];
    [self.viewPhoneBack addSubview:self.labelPhone];
    //初始化页面
    [self resetViewWithModel:nil];
}

#pragma mark - 点击事件
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self endEditing:true];
}
- (void)btnClick:(UIButton *)sender{
    [NSObject clickFeedback];
    [sender addClickAnimate];
    switch (sender.tag) {
        case 1:
        {
            [self removeFromSuperview];
            self.textView.text = @"";
            self.labelPlaceholder.hidden = false;
            [self resetEnviarBtn:false];
            [self.labelNum fitTitle:[NSString stringWithFormat:@"0/%d",self.maxCharacterCount] variable:0];
            self.labelNum.rightCenterY = XY(self.labelNum.right, self.labelNum.centerY);
        }
            break;
        case 2:
        {
            [self requestSubmit];
        }
            break;
        case 3:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = self.phoneNumber;
            [GlobalMethod showAlert:@"Copia éxito"];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - textView delegate
- (void)textViewDidChange:(UITextView *)textView{
    self.labelPlaceholder.hidden = isStr(textView.text);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 计算输入文字的长度
    NSString * newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger markLength = newText.length;
    
    // 显示文字输入个数
    NSInteger textNumber = newText.length<=self.maxCharacterCount?newText.length:self.maxCharacterCount;
    [self.labelNum fitTitle:[NSString stringWithFormat:@"%ld/%d",textNumber,self.maxCharacterCount] variable:0];
    self.labelNum.rightCenterY = XY(self.labelNum.right, self.labelNum.centerY);
    
    // 按钮点击状态
    [self resetEnviarBtn:isStrDeleteSpaces(newText)];
    // 截取超过最大字符数的文本
    if (newText.length > self.maxCharacterCount) {
        newText = [newText substringToIndex:self.maxCharacterCount];
        textView.text = newText;
        // 移动光标到文本的末尾
        // 延迟设置光标位置
        dispatch_async(dispatch_get_main_queue(), ^{
            UITextPosition *endPosition = [textView positionFromPosition:textView.beginningOfDocument offset:newText.length];
            UITextRange *endRange = [textView textRangeFromPosition:endPosition toPosition:endPosition];
            [textView setSelectedTextRange:endRange];
        });
    }
    // 判断文字长度是否超过限制
    return markLength <= self.maxCharacterCount;
}

- (void)moveCursorToEndOfTextView:(UITextView *)textView {
    // 获取文本的末尾位置
    UITextPosition *endPosition = [textView positionFromPosition:textView.beginningOfDocument offset:textView.text.length];
    // 创建一个新的文本范围，从末尾位置到末尾位置（即光标在末尾）
    UITextRange *endRange = [textView textRangeFromPosition:endPosition toPosition:endPosition];
    // 设置新的选择范围（光标移动到文本末尾）
    [textView setSelectedTextRange:endRange];
}

- (void)resetEnviarBtn:(BOOL)available{
    self.btnOK.userInteractionEnabled = available;
    self.btnOK.alpha = available ? 1 : 0.5;
}

#pragma mark - 刷新view
- (void)resetViewWithModel:(id)model{
    self.btnClose.rightTop = XY(self.viewBack.width, 0);
    [self.labelTitle fitTitle:@"Realimentación" variable:0];
    self.labelTitle.centerXTop = XY(self.viewBack.width/2, Ratio(50));
    
    [self.labelContent fitTitle:@"Detalla el problema que ha encontrado:" variable:self.viewBack.width-2*30];
    self.labelContent.leftTop = XY(30, self.labelTitle.bottom+Ratio(30));
    
    self.viewTextBack.widthHeight = XY(self.viewBack.width-2*self.labelContent.left, Ratio(182));
    self.viewTextBack.leftTop = XY(self.labelContent.left, self.labelContent.bottom+Ratio(10));
    
    [self.labelNum fitTitle:[NSString stringWithFormat:@"0/%d",self.maxCharacterCount] variable:0];
    self.labelNum.rightBottom = XY(self.viewTextBack.width-10, self.viewTextBack.height-8);
    CGFloat textViewTop = Ratio(12);
    self.textView.widthHeight = XY(self.viewTextBack.width-2*Ratio(12), self.labelNum.top-Ratio(12)-textViewTop);
    self.textView.leftTop = XY(Ratio(12), textViewTop);
    self.labelPlaceholder.leftTop = XY(Ratio(17), Ratio(19));
    
    self.btnOK.widthHeight = XY(self.viewTextBack.width, BUTTON_HEIGHT);
    self.btnOK.leftTop = XY(self.viewTextBack.left, self.viewTextBack.bottom+Ratio(30));
    [GlobalMethod setRoundView:self.btnOK color:[UIColor clearColor] numRound:self.btnOK.height/2 width:0];
    
    [self.labelSubContent fitTitle:@"También puede comunicarse directamente con el servicio al cliente:" variable:self.btnOK.width];
    self.labelSubContent.leftTop = XY(self.btnOK.left, self.btnOK.bottom+Ratio(25));
    
    self.btnCopy.widthHeight = XY(Ratio(80), BUTTON_HEIGHT);
    self.btnCopy.rightTop = XY(self.btnOK.right, self.labelSubContent.bottom+Ratio(10));
    [GlobalMethod setRoundView:self.btnCopy color:[UIColor clearColor] numRound:self.btnOK.height/2 width:0];
    
    self.viewPhoneBack.widthHeight = XY(self.btnOK.width-16-self.btnCopy.width, self.btnCopy.height);
    self.viewPhoneBack.leftCenterY = XY(self.btnOK.left, self.btnCopy.centerY);
    [GlobalMethod setRoundView:self.viewPhoneBack color:COLOR_LINE numRound:self.viewPhoneBack.height/2 width:1];
    
    [self.labelPhone fitTitle:@"**************" variable:0];
    self.labelPhone.centerXCenterY = XY(self.viewPhoneBack.width/2, self.viewPhoneBack.height/2);
    
    self.viewBack.height = self.viewPhoneBack.bottom+BUTTON_HEIGHT;
    [GlobalMethod setRoundView:self.viewBack color:[UIColor clearColor] numRound:16 width:0];
    self.viewBack.centerXCenterY = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}

#pragma mark - request
- (void)requestCustomerServiceInfo{
    [RequestApi requestCustomerServiceInfoWithDelegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        ModelService * serviceModel = [GlobalMethod exchangeDicToModel:response modelName:@"ModelService"];
        // 电话
        self.phoneNumber = readStr(serviceModel.phone);
        [self.labelPhone fitTitle:self.phoneNumber variable:self.viewPhoneBack.width-2*LEFT_MARDIN];
        self.labelPhone.centerXCenterY = XY(self.viewPhoneBack.width/2, self.viewPhoneBack.height/2);
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

- (void)requestSubmit{
    NSString * className = NSStringFromClass([Global_Nav.visibleViewController class]);
    [RequestApi requestComplaintWithTitle:isStr(self.vcName)?self.vcName:className content:[self.textView.text removeHeadAndTailSpace] delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        [GlobalMethod showAlert:@"Sent successfully"];
        [self removeFromSuperview];
        self.textView.text = @"";
        self.labelPlaceholder.hidden = false;
        // 按钮点击状态
        [self resetEnviarBtn:false];
        [self.labelNum fitTitle:[NSString stringWithFormat:@"0/%d",self.maxCharacterCount] variable:0];
        self.labelNum.rightCenterY = XY(self.labelNum.right, self.labelNum.centerY);

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {

        [GlobalMethod showAlert: errorStr];
        
    }];
}


@end
